/**
 * @Author: gan
 * @Description:
 * @File:  jwt
 * @Version: 1.0.0
 * @Date: 2022/6/15 4:20 下午
 */

package middleware

import (
	"gin-canteen-src/enums"
	"gin-canteen-src/global"
	commonResponse "gin-canteen-src/model/common/response"
	"gin-canteen-src/utils"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"strconv"
	"time"
)

func JWTAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.Request.Header.Get("x-token")
		if token == "" {
			commonResponse.FailWithMessage(enums.NoPermission, enums.GetMsg(enums.NoPermission), c)
			c.Abort()
			return
		}

		j := utils.NewJWT()
		// parseToken 解析token包含的信息
		claims, err := j.ParseToken(token)
		if err != nil {
			if err == utils.TokenExpired {
				commonResponse.FailWithMessage(enums.NoPermission, enums.GetMsg(enums.NoPermission), c)
				c.Abort()
				return
			}
			commonResponse.FailWithMessage(enums.NoPermission, err.Error(), c)
			c.Abort()
			return
		}

		if claims.ExpiresAt-time.Now().Unix() < claims.BufferTime {
			claims.ExpiresAt = time.Now().Unix() + global.GloConfig.JWT.ExpiresTime
			newToken, _ := j.CreateTokenByOldToken(token, *claims)
			newClaims, _ := j.ParseToken(newToken)

			c.Header("new-token", newToken)
			c.Header("new-expires-at", strconv.FormatInt(newClaims.ExpiresAt, 10))

			if global.GloConfig.System.UseMultipoint {
				timer := time.Duration(global.GloConfig.JWT.ExpiresTime) * time.Second
				err = global.GloRedis.Set(c, newToken, newClaims.Username, timer).Err()
				if err != nil {
					global.GloLogger.Error("设置登录状态失败", zap.Error(err))
					commonResponse.FailWithMessage(enums.ErrorCache, "设置登录状态失败", c)
				}
			}
		}
		c.Set("claims", claims)
		c.Next()
	}
}
